import React, {Component} from 'react';
import classNames from 'classnames';

import {Input, Button } from 'antd';
const InputGroup = Input.Group;

import noop from 'util/noop';

export default class SearchSelect extends Component {
    static defaultProps = {
        placeholder: '',
        size: 'default',
        onSearch: noop
    }


    constructor(props) {
        super(props);

        this.state = {
            focus: false,
            value: ''
        }
    }


    handleChange(e) {
        this.setState({
            value: e.target.value
        })
    }


    handleFocusAndBlur(e) {
        this.setState({
            focus: e.target == document.activeElement
        })
    }


    handleSearch() {
        this.props.onSearch(this.state.value);
    }


    render() {
        const {placeholder, size} = this.props;
        const {focus, value} = this.state;

        const searchCls = classNames('ant-search-input', {'ant-search-input-focus': focus});

        const btnCls = classNames('ant-search-btn', {'ant-search-btn-noempty': !!value.trim()});

        return (
            <InputGroup className={searchCls}>
                <Input size="large"
                       placeholder={placeholder}
                       value={value}

                       onChange={(e)=>this.handleChange(e)}
                       onFocus={(e)=>this.handleFocusAndBlur(e)}
                       onBlur={(e)=>this.handleFocusAndBlur(e)}
                       onPressEnter={()=>this.handleSearch()}/>

                <div className="ant-input-group-wrap">
                    <Button icon="search"
                            className={btnCls}
                            size={size}
                            onClick={()=>this.handleSearch()}/>
                </div>
            </InputGroup>
        )
    }
}